#! /usr/bin/python
# -*- coding: cp1250 -*-

import os
import psycopg2

class Pg:
    """ """
    def __init__(self, query, debugmode=False):
        """ """
        self.server = '127.0.0.1'
        self.database = 'work'
        #self.user = 'postgres'
        #self.user = 'vpresovsky'

        from pepe.p_oslevel.system_variables import main as sv
        username = sv('USERNAME')

        #u = 
        u = raw_input("""\tRole (default is 'public'): """)
        if u == '':
            self.user = 'postgres'
        else:
            self.user = u[:]
        
        self.error = ''
        """
        try:
            #self.con = psycopg2.connect("dbname='work' user='postgres' host='localhost' password='xxx'");
            self.con = psycopg2.connect("dbname='work' user='postgres' host='localhost'");
        except:
            self.error = "I am unable to connect to the database"
        """ 
        cstring = "dbname='%s' user='%s' host='%s'" % (self.database, self.user, self.server)
        #self.con = psycopg2.connect("dbname='wrk2' user='postgres' host='127.0.0.1'")
        self.con = psycopg2.connect(cstring)

        self.cur = self.con.cursor()
        # send query

        #ce_type = 'win1250'
        #if os.name == 'posix': ce_type = 'UTF-8'
        #ce = "SET client_encoding TO '%s';\n" % (ce_type)
        #of = open('/rdisk/test.txt', 'w')
        #of.write(ce + query)
        #of.close()

        #self.cur.execute(ce + query)
        if debugmode == True: print "-", query, "-"
        self.cur.execute(query)
        self.con.commit()

    def __getitem__( self , index ):
        row = self.cur.fetchone()
        if row:
            return row
        else:
            raise IndexError

if __name__ == "__main__":
    """ http://www.postgresql.org/files/documentation/books/aw_pgsql/node183.html
    """
    #for r in Pg('select * from pg_tables'):
    #select datname from pg_database;
    for r in Pg('select * from pg_database'):
        # listing databases
        print r[0], r
    
    """
    #for r in Pg('select * from pg_class'):
    for r in Pg('select * from pg_tables'):
        # listing tables
        print r[0], r
    """
